package com.example.controller;

import com.example.domain.Result;
import com.example.domain.Student;
import com.example.service.StudentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/student")
public class StudentController extends MyController {

    @Autowired
    private StudentService studentService;

    @PostMapping("/list")
    public Result list(Student student) {

        PageInfo<Student> pageInfo = studentService.selectStudentList(student);
        return success(pageInfo);
    }

    @PostMapping("/add")
    public Result add(Student student) {
        studentService.saveStudent(student);
        return success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Long id) {
        Student student = this.studentService.selectById(id);
        return success(student);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") Long id) {
        this.studentService.deleteById(id);
        return success();
    }

    @PostMapping("/login")
    public Result login(String username, String password, HttpSession session) {
        Student student = this.studentService.selectStudentByUsernameAndPassword(username, password);
        if (student == null) {
            return error("用户名或密码错误");
        }
        session.setAttribute("login", student);
        Map<String, Objects> data = new HashMap() {{
            put("nickName", student.getTrueName());
            put("userId", student.getStudentId());
            put("roleKey", "STUDENT");
        }};
        return success(data);
    }

    @PostMapping("/exit")
    public Result exit(HttpSession session) {
        session.invalidate();

        return success();
    }

    @PostMapping("/owner")
    public Result owner(String trueName, String gender,
                        String password, HttpSession session) {
        Student student = (Student) session.getAttribute("login");
        student.setTrueName(trueName);
        student.setGender(gender);
        student.setPassword(password);
        studentService.saveStudent(student);
        return success();
    }

    @GetMapping("/info")
    public Result info(HttpSession session) {
        Student student = (Student) session.getAttribute("login");
        return success(student);
    }
}
